#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#pragma warning (disable : 4996)

int my_itoa(char* str, int num)        //简单数字转字符函数
{
	assert(str);
	char temp[5] = { 0 };
	int count = 0;           //位数
	while (num){             //每次将num个位转换为字符格式存在temp (num逆序字符串)
		temp[count++] = (num % 10) + '0';
		num /= 10;
	}
	for (int i = 0; i < count; i++){
		str[i] = temp[count - 1 - i];     //再将temp中字符逆序赋给str中，得到num字符串
	}
	return count;
}

char* compressString(char* S){
	int len = strlen(S);
	if (len <= 2 || len > 50000){       //范围[0,50000],如果长度为2一定不会变短
		return S;
	}
	char* newstr = (char*)malloc(sizeof(char)* 2 * len);    //申请新空间存放新字符串
	int pos = 0;                   
	int num = 1;                //字符个数
	//遍历字符串将压缩结果存放到newstr中
	for (int i = 0; i < len; i++){             
		if (S[i] == S[i + 1]){
			num++;
		}
		else{
			newstr[pos++] = S[i];
			pos += my_itoa(newstr + pos, num);     //通过my_itoa将数字转为字符存在newstr中合适位置
			num = 1;                  //统计下一个字符个数
		}
	}
	newstr[pos] = '\0';
	if (len <= strlen(newstr)){               //如果新字符串长度没有短于原长度
		free(newstr);
		return S;
	}
	return newstr;
	//return strlen(newstr) < len ? newstr : S;
}

int main()
{
	printf("%s\n", compressString("rrrrrLLLLLPPPPPPRRRRRgggNNNNNVVVVVVVVVVDDDDDDDDDDIIIIIIIIIIlllllllAAAAqqqqqqqbbbNNNNffffff"));
	return 0;
}